﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFTools {
    public class SlnTools {
        public static string? GenerateSlnCodePhase(List<string> listProjectNames) {
            if (listProjectNames == null || listProjectNames.Count == 0) {
                return null;
            }
            // 去掉空的
            StringBuilder sb = new StringBuilder();
            listProjectNames = listProjectNames.Where(projectName => !string.IsNullOrEmpty(projectName)).ToList();
            foreach (string projectName in listProjectNames) {
                sb.Append($"Project(\"{{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}}\") = \"{projectName}\", \"..\\{projectName}\\{projectName}.vcproj\", \"{{B6BC4E64-F042-44C4-807F-2F0CE9B5516C}}\"\r\n" +
                    $"EndProject\n");
            }
            return sb.ToString();
        }
        public static bool AddProjectToSln(string slnPath, List<string> listProjects) {
            if (listProjects == null || listProjects.Count == 0) {
                return false;
            }
            // 读取 sln
            StreamReader sr = new StreamReader(slnPath);
            string content = sr.ReadToEnd();
            sr.Close();
            if (string.IsNullOrEmpty(content)) {
                return false;
            }
            // 寻找插入点，即最后一次出现 EndProject 的位置
            string targetSeq = "EndProject";
            int insertPoint = content.LastIndexOf(targetSeq) + targetSeq.Length + 1;
            // 生成要插入的内容
            string ?contentToBeInsert = GenerateSlnCodePhase(listProjects);
            if (string.IsNullOrEmpty(contentToBeInsert)) {
                return false;
            }
            // 插入
            content = content.Insert(insertPoint, contentToBeInsert);
            // 将修改后的内容写回文件
            StreamWriter sw = new StreamWriter(slnPath);
            sw.Write(content);
            sw.Close();

            return true;
        }
    }
}
